<template>
  <div class="app-container">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <span class="main-title">自动组卷</span>
        </div>
      </template>
      <el-form ref="formRef" :model="form" :rules="rules" label-width="100px">
        <!-- 试卷基本信息部分 -->
        <div class="section-header">
          <i class="el-icon-info"></i>
          <span>试卷信息</span>
        </div>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="试卷名称" prop="paper.paperName">
              <el-input v-model="form.paper.paperName" placeholder="请输入试卷名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="考试班级" prop="paper.classId">
              <el-select v-model="form.paper.classId" placeholder="请选择班级" filterable>
                <el-option
                  v-for="item in classList"
                  :key="item.classId"
                  :label="item.className"
                  :value="item.classId"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="考试时长" prop="paper.duration">
              <el-input-number v-model="form.paper.duration" :min="10" :max="1440" :step="10" 
                class="w-100" append-label="分钟" @change="handleDurationChange" />
            </el-form-item>
          </el-col>
          <el-col :span="16">
            <el-form-item label="考试时间" required>
              <el-row :gutter="10">
                <el-col :span="11">
                  <el-form-item prop="paper.startTime">
                    <el-date-picker 
                      v-model="form.paper.startTime" 
                      type="datetime" 
                      placeholder="开始时间"
                      value-format="YYYY-MM-DD HH:mm:ss"
                      format="YYYY-MM-DD HH:mm"
                      :disabled-date="disabledDate"
                      :disabled-time="disabledTime"
                      @change="handleStartTimeChange"
                      class="w-100" 
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="2" class="text-center">至</el-col>
                <el-col :span="11">
                  <el-form-item prop="paper.endTime">
                    <el-date-picker 
                      v-model="form.paper.endTime" 
                      type="datetime" 
                      placeholder="结束时间"
                      value-format="YYYY-MM-DD HH:mm:ss"
                      format="YYYY-MM-DD HH:mm"
                      :disabled-date="disabledEndDate"
                      class="w-100" 
                    />
                  </el-form-item>
                </el-col>
              </el-row>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 组卷信息部分 -->
        <div class="section-header">
          <i class="el-icon-setting"></i>
          <span>组卷信息</span>
        </div>
        <!-- 分数设置选项 -->
        <el-row>
          <el-col :span="24" class="score-setting-toggle">
            <el-switch
              v-model="useCustomScores"
              active-text="统一设置分数"
              inactive-text="采用原有分数"
              @change="handleScoreTypeChange"
            />
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="章节范围" prop="chapterIds">
              <el-tree-select
                v-model="form.chapterIds"
                :data="chapterTree"
                :props="{ 
                  label: 'chapterName', 
                  value: 'chapterId', 
                  children: 'children'
                }"
                :render-after-expand="false"
                show-checkbox
                :check-strictly="false"
                multiple
                default-expand-all
                node-key="chapterId"
                :collapse-tags="false"
                :max-collapse-tags="7"
                collapse-tags-tooltip
                placeholder="请选择章节"
                style="width: 100%;"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 单选题设置 -->
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="单选题个数">
              <el-input-number v-model="form.singleChoiceCount" :min="0" :max="50" class="w-100" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="难度范围">
              <el-row :gutter="10">
                <el-col :span="11">
                  <el-tooltip
                    :content="getDifficultyText(form.singleChoiceMinDifficulty)"
                    placement="top"
                    :show-after="300"
                  >
                    <el-rate
                      v-model="form.singleChoiceMinDifficulty"
                      :max="5"
                      :texts="difficultyTexts"
                      :show-text="false"
                      @change="handleMinDifficultyChange('singleChoice')"
                    />
                  </el-tooltip>
                </el-col>
                <el-col :span="2" class="text-center">至</el-col>
                <el-col :span="11">
                  <el-tooltip
                    :content="getDifficultyText(form.singleChoiceMaxDifficulty)"
                    placement="top"
                    :show-after="300"
                  >
                    <el-rate
                      v-model="form.singleChoiceMaxDifficulty"
                      :max="5"
                      :texts="difficultyTexts"
                      :show-text="false"
                      @change="handleMaxDifficultyChange('singleChoice')"
                    />
                  </el-tooltip>
                </el-col>
              </el-row>
            </el-form-item>
          </el-col>
          <el-col :span="8" v-if="useCustomScores">
            <el-form-item label="单选题分值">
              <el-input-number v-model="form.singleChoiceScore" :min="0" :max="20" :precision="1" :step="0.5" class="w-100" />
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 多选题设置 -->
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="多选题个数">
              <el-input-number v-model="form.multiChoiceCount" :min="0" :max="30" class="w-100" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="难度范围">
              <el-row :gutter="10">
                <el-col :span="11">
                  <el-tooltip
                    :content="getDifficultyText(form.multiChoiceMinDifficulty)"
                    placement="top"
                    :show-after="300"
                  >
                    <el-rate
                      v-model="form.multiChoiceMinDifficulty"
                      :max="5"
                      :texts="difficultyTexts"
                      :show-text="false"
                      @change="handleMinDifficultyChange('multiChoice')"
                    />
                  </el-tooltip>
                </el-col>
                <el-col :span="2" class="text-center">至</el-col>
                <el-col :span="11">
                  <el-tooltip
                    :content="getDifficultyText(form.multiChoiceMaxDifficulty)"
                    placement="top"
                    :show-after="300"
                  >
                    <el-rate
                      v-model="form.multiChoiceMaxDifficulty"
                      :max="5"
                      :texts="difficultyTexts"
                      :show-text="false"
                      @change="handleMaxDifficultyChange('multiChoice')"
                    />
                  </el-tooltip>
                </el-col>
              </el-row>
            </el-form-item>
          </el-col>
          <el-col :span="8" v-if="useCustomScores">
            <el-form-item label="多选题分值">
              <el-input-number v-model="form.multiChoiceScore" :min="0" :max="20" :precision="1" :step="0.5" class="w-100" />
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 判断题设置 -->
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="判断题个数">
              <el-input-number v-model="form.judgmentCount" :min="0" :max="30" class="w-100" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="难度范围">
              <el-row :gutter="10">
                <el-col :span="11">
                  <el-tooltip
                    :content="getDifficultyText(form.judgmentMinDifficulty)"
                    placement="top"
                    :show-after="300"
                  >
                    <el-rate
                      v-model="form.judgmentMinDifficulty"
                      :max="5"
                      :texts="difficultyTexts"
                      :show-text="false"
                      @change="handleMinDifficultyChange('judgment')"
                    />
                  </el-tooltip>
                </el-col>
                <el-col :span="2" class="text-center">至</el-col>
                <el-col :span="11">
                  <el-tooltip
                    :content="getDifficultyText(form.judgmentMaxDifficulty)"
                    placement="top"
                    :show-after="300"
                  >
                    <el-rate
                      v-model="form.judgmentMaxDifficulty"
                      :max="5"
                      :texts="difficultyTexts"
                      :show-text="false"
                      @change="handleMaxDifficultyChange('judgment')"
                    />
                  </el-tooltip>
                </el-col>
              </el-row>
            </el-form-item>
          </el-col>
          <el-col :span="8" v-if="useCustomScores">
            <el-form-item label="判断题分值">
              <el-input-number v-model="form.judgmentScore" :min="0" :max="20" :precision="1" :step="0.5" class="w-100" />
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 填空题设置 -->
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="填空题个数">
              <el-input-number v-model="form.fillBlankCount" :min="0" :max="20" class="w-100" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="难度范围">
              <el-row :gutter="10">
                <el-col :span="11">
                  <el-tooltip
                    :content="getDifficultyText(form.fillBlankMinDifficulty)"
                    placement="top"
                    :show-after="300"
                  >
                    <el-rate
                      v-model="form.fillBlankMinDifficulty"
                      :max="5"
                      :texts="difficultyTexts"
                      :show-text="false"
                      @change="handleMinDifficultyChange('fillBlank')"
                    />
                  </el-tooltip>
                </el-col>
                <el-col :span="2" class="text-center">至</el-col>
                <el-col :span="11">
                  <el-tooltip
                    :content="getDifficultyText(form.fillBlankMaxDifficulty)"
                    placement="top"
                    :show-after="300"
                  >
                    <el-rate
                      v-model="form.fillBlankMaxDifficulty"
                      :max="5"
                      :texts="difficultyTexts"
                      :show-text="false"
                      @change="handleMaxDifficultyChange('fillBlank')"
                    />
                  </el-tooltip>
                </el-col>
              </el-row>
            </el-form-item>
          </el-col>
          <el-col :span="8" v-if="useCustomScores">
            <el-form-item label="填空题分值">
              <el-input-number v-model="form.fillBlankScore" :min="0" :max="20" :precision="1" :step="0.5" class="w-100" />
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 简答题设置 -->
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="简答题个数">
              <el-input-number v-model="form.essayCount" :min="0" :max="10" class="w-100" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="难度范围">
              <el-row :gutter="10">
                <el-col :span="11">
                  <el-tooltip
                    :content="getDifficultyText(form.essayMinDifficulty)"
                    placement="top"
                    :show-after="300"
                  >
                    <el-rate
                      v-model="form.essayMinDifficulty"
                      :max="5"
                      :texts="difficultyTexts"
                      :show-text="false"
                      @change="handleMinDifficultyChange('essay')"
                    />
                  </el-tooltip>
                </el-col>
                <el-col :span="2" class="text-center">至</el-col>
                <el-col :span="11">
                  <el-tooltip
                    :content="getDifficultyText(form.essayMaxDifficulty)"
                    placement="top"
                    :show-after="300"
                  >
                    <el-rate
                      v-model="form.essayMaxDifficulty"
                      :max="5"
                      :texts="difficultyTexts"
                      :show-text="false"
                      @change="handleMaxDifficultyChange('essay')"
                    />
                  </el-tooltip>
                </el-col>
              </el-row>
            </el-form-item>
          </el-col>
          <el-col :span="8" v-if="useCustomScores">
            <el-form-item label="简答题分值">
              <el-input-number v-model="form.essayScore" :min="0" :max="30" :precision="1" :step="1" class="w-100" />
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 按钮区域 -->
        <el-form-item class="button-group">
          <el-button type="primary" @click="handlePreview">预览</el-button>
          <el-button @click="resetForm">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 预览试卷对话框 -->
    <el-dialog 
      v-model="previewDialogVisible" 
      title="试卷预览" 
      width="80%" 
      append-to-body
      @opened="renderMathInPreview"
    >
      <div ref="previewContainer" class="paper-preview">
        <div class="paper-header">
          <h1>{{ form.paper.paperName || '未命名试卷' }}</h1>
          <div class="paper-info">
            <p>考试时长：{{ form.paper.duration }}分钟</p>
            <p>总分：{{ calculateTotalScore() }}分</p>
          </div>
        </div>
        <div v-loading="previewLoading" class="paper-content">
          <!-- 单选题预览 -->
          <div v-if="previewData.singleChoice && previewData.singleChoice.length > 0" class="question-section">
            <h2>{{ getSectionTitle('singleChoice') }}（共{{ previewData.singleChoice.length }}题，共{{ calculateSectionScore('singleChoice') }}分）</h2>            <div v-for="(question, index) in previewData.singleChoice" :key="'single-'+index" class="question-item">
              <div class="question-title">{{ index + 1 }}. <span class="score-tag">(本题{{ getQuestionScore(question) }}分)</span> <span v-html="processContent(question.questionContent)"></span></div>
              <div class="question-options">
                <div v-for="option in question.options" :key="option.optionLabel" class="question-option">
                  <span class="option-label">{{ option.optionLabel }}.</span>
                  <span class="option-content" v-html="processContent(option.optionContent)"></span>
                </div>
              </div>
            </div>
          </div>

          <!-- 多选题预览 -->
          <div v-if="previewData.multiChoice && previewData.multiChoice.length > 0" class="question-section">
            <h2>{{ getSectionTitle('multiChoice') }}（共{{ previewData.multiChoice.length }}题，共{{ calculateSectionScore('multiChoice') }}分）</h2>
            <div v-for="(question, index) in previewData.multiChoice" :key="'multi-'+index" class="question-item">
              <div class="question-title">{{ index + 1 }}. <span class="score-tag">(本题{{ getQuestionScore(question) }}分)</span> <span v-html="processContent(question.questionContent)"></span></div>
              <div class="question-options">
                <div v-for="option in question.options" :key="option.optionLabel" class="question-option">
                  <span class="option-label">{{ option.optionLabel }}.</span>
                  <span class="option-content" v-html="processContent(option.optionContent)"></span>
                </div>
              </div>
            </div>
          </div>

          <!-- 判断题预览 -->
          <div v-if="previewData.judgment && previewData.judgment.length > 0" class="question-section">
            <h2>{{ getSectionTitle('judgment') }}（共{{ previewData.judgment.length }}题，共{{ calculateSectionScore('judgment') }}分）</h2>
            <div v-for="(question, index) in previewData.judgment" :key="'judgment-'+index" class="question-item">
              <div class="question-title">{{ index + 1 }}. <span class="score-tag">(本题{{ getQuestionScore(question) }}分)</span> <span v-html="processContent(question.questionContent)"></span></div>
              <div class="question-options">
                <div class="question-option">
                  <span class="option-label">A.</span>
                  <span class="option-content">正确</span>
                </div>
                <div class="question-option">
                  <span class="option-label">B.</span>
                  <span class="option-content">错误</span>
                </div>
              </div>
            </div>
          </div>

          <!-- 填空题预览 -->
          <div v-if="previewData.fillBlank && previewData.fillBlank.length > 0" class="question-section">
            <h2>{{ getSectionTitle('fillBlank') }}（共{{ previewData.fillBlank.length }}题，共{{ calculateSectionScore('fillBlank') }}分）</h2>
            <div v-for="(question, index) in previewData.fillBlank" :key="'fill-'+index" class="question-item">
              <div class="question-title">{{ index + 1 }}. <span class="score-tag">(本题{{ getQuestionScore(question) }}分)</span> <span v-html="processContent(renderFillBlankQuestion(question.questionContent))"></span></div>
            </div>
          </div>

          <!-- 简答题预览 -->
          <div v-if="previewData.essay && previewData.essay.length > 0" class="question-section">
            <h2>{{ getSectionTitle('essay') }}（共{{ previewData.essay.length }}题，共{{ calculateSectionScore('essay') }}分）</h2>            <div v-for="(question, index) in previewData.essay" :key="'essay-'+index" class="question-item">
              <div class="question-title">{{ index + 1 }}. <span class="score-tag">(本题{{ getQuestionScore(question) }}分)</span> <span v-html="processContent(question.questionContent)"></span></div>            </div>
          </div>

          <div v-if="!previewData.singleChoice?.length && !previewData.multiChoice?.length && !previewData.judgment?.length && !previewData.fillBlank?.length && !previewData.essay?.length" class="empty-data">
            请先生成试卷
          </div>
        </div>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="previewDialogVisible = false">关闭</el-button>
          <el-button type="primary" @click="handleSubmit">确认并创建</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed, nextTick } from 'vue';
import { ElMessage } from 'element-plus';
import { useRouter } from 'vue-router';
import { listGrade, getMyClasses } from "@/api/manage/grade";
import { getChapters, createAutomaticPaper, previewAutomaticPaper } from "@/api/manage/paper";
import useUserStore from '@/store/modules/user';

const router = useRouter();
const formRef = ref(null);
const chapterTree = ref([]);
const classList = ref([]);
const previewDialogVisible = ref(false);
const previewLoading = ref(false);
const previewContainer = ref(null);
const useCustomScores = ref(true); // 控制是否使用自定义分数
const now = new Date(); // 当前时间

// 难度文本
const difficultyTexts = ['简单', '较简单', '中等', '较难', '困难'];

// 获取难度文本
const getDifficultyText = (value) => {
  return difficultyTexts[Math.round(value) - 1] || '未设置';
};

// 处理最小难度变化，确保最小难度不大于最大难度
const handleMinDifficultyChange = (type) => {
  const minKey = `${type}MinDifficulty`;
  const maxKey = `${type}MaxDifficulty`;
  
  if (form[minKey] > form[maxKey]) {
    form[maxKey] = form[minKey];
  }
};

// 处理最大难度变化，确保最大难度不小于最小难度
const handleMaxDifficultyChange = (type) => {
  const minKey = `${type}MinDifficulty`;
  const maxKey = `${type}MaxDifficulty`;
  
  if (form[maxKey] < form[minKey]) {
    form[minKey] = form[maxKey];
  }
};

// 禁用今天之前的日期
const disabledDate = (time) => {
  return time.getTime() < now.getTime() - 8.64e7; // 禁用昨天及之前的日期
};

// 禁用今天之前的时间
const disabledTime = (date) => {
  if (date && date.getDate() === now.getDate() && 
      date.getMonth() === now.getMonth() && 
      date.getFullYear() === now.getFullYear()) {
    return {
      hours: Array.from(Array(now.getHours()).keys()),
      minutes: date && date.getHours() === now.getHours() 
        ? Array.from(Array(now.getMinutes()).keys()) 
        : []
    };
  }
  return {
    hours: [],
    minutes: []
  };
};

// 禁用结束时间小于开始时间+考试时长的日期
const disabledEndDate = (time) => {
  if (!form.paper.startTime) return false;
  
  const startTime = new Date(form.paper.startTime);
  const minEndTime = new Date(startTime.getTime() + form.paper.duration * 60 * 1000);
  
  return time.getTime() < minEndTime.getTime();
};

// 格式化本地时间
const formatLocalDateTime = (date) => {
  if (!date) return '';
  const d = new Date(date);
  
  const year = d.getFullYear();
  const month = String(d.getMonth() + 1).padStart(2, '0');
  const day = String(d.getDate()).padStart(2, '0');
  const hours = String(d.getHours()).padStart(2, '0');
  const minutes = String(d.getMinutes()).padStart(2, '0');
  const seconds = String(d.getSeconds()).padStart(2, '0');
  
  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
};

// 处理考试时长变化
const handleDurationChange = () => {
  if (form.paper.startTime && form.paper.endTime) {
    const startTime = new Date(form.paper.startTime);
    const newEndTime = new Date(startTime.getTime() + form.paper.duration * 60 * 1000);
    
    // 如果当前结束时间小于新的最小结束时间，则更新结束时间
    const currentEndTime = new Date(form.paper.endTime);
    if (currentEndTime.getTime() < newEndTime.getTime()) {
      form.paper.endTime = formatLocalDateTime(newEndTime);
    }
  }
};

// 处理开始时间变化
const handleStartTimeChange = () => {
  if (form.paper.startTime) {
    const startTime = new Date(form.paper.startTime);
    const newEndTime = new Date(startTime.getTime() + form.paper.duration * 60 * 1000);
    form.paper.endTime = formatLocalDateTime(newEndTime);
  }
};

// 获取题型标题（自动编号）
const getSectionTitle = (type) => {
  const titles = {
    'singleChoice': '单选题',
    'multiChoice': '多选题',
    'judgment': '判断题',
    'fillBlank': '填空题',
    'essay': '简答题'
  };
  
  // 计算当前题型的顺序编号
  let index = 1;
  const types = ['singleChoice', 'multiChoice', 'judgment', 'fillBlank', 'essay'];
  
  for (const t of types) {
    if (t === type) {
      break;
    }
    
    if (previewData[t]?.length > 0) {
      index++;
    }
  }
  
  // 转换为中文数字
  const chineseNumbers = ['一', '二', '三', '四', '五'];
  return `${chineseNumbers[index-1]}、${titles[type]}`;
};

// 获取题目分值展示文字
const getScoreText = (questions) => {
  if (!questions || questions.length === 0) return '原分值';
  
  // 检查是否所有题目都有相同分值
  const firstScore = questions[0].score;
  const allSameScore = questions.every(q => q.score === firstScore);
  
  if (allSameScore) {
    return `${firstScore}分`;
  } else {
    return '不同分值';
  }
};

// 获取单个题目分数
const getQuestionScore = (question) => {
  if (!question) return 0;
  
  if (!useCustomScores.value) {
    // 使用题目原有分数
    return question.score || 0;
  }
  
  // 使用统一设置的分数
  switch (question.questionType) {
    case 0: return form.singleChoiceScore;
    case 1: return form.multiChoiceScore;
    case 2: return form.judgmentScore;
    case 3: return form.fillBlankScore;
    case 4: return form.essayScore;
    default: return 0;
  }
};

// 计算某个题型的总分
const calculateSectionScore = (type) => {
  const questions = previewData[type] || [];
  if (questions.length === 0) return 0;
  
  if (!useCustomScores.value) {
    // 使用题目原有分数计算总分
    return questions.reduce((sum, q) => sum + (q.score || 0), 0);
  } else {
    // 使用统一设置的分数
    const scoreKey = `${type}Score`;
    return questions.length * form[scoreKey];
  }
};

// 预览数据
const previewData = reactive({
  singleChoice: [],
  multiChoice: [],
  judgment: [],
  fillBlank: [],
  essay: []
});

// 表单数据
const form = reactive({
  paper: {
    paperName: '',
    classId: '',
    duration: 120,
    startTime: '',
    endTime: '',
    status: 0, // 默认草稿状态
    useOriginalScore: false
  },
  chapterIds: [],
  // 单选题设置
  singleChoiceCount: 10,
  singleChoiceScore: 2,
  singleChoiceMinDifficulty: 1,
  singleChoiceMaxDifficulty: 5,
  // 多选题设置
  multiChoiceCount: 5,
  multiChoiceScore: 4,
  multiChoiceMinDifficulty: 1,
  multiChoiceMaxDifficulty: 5,
  // 判断题设置
  judgmentCount: 10,
  judgmentScore: 1,
  judgmentMinDifficulty: 1,
  judgmentMaxDifficulty: 5,
  // 填空题设置
  fillBlankCount: 5,
  fillBlankScore: 4,
  fillBlankMinDifficulty: 1,
  fillBlankMaxDifficulty: 5,
  // 简答题设置
  essayCount: 3,
  essayScore: 10,
  essayMinDifficulty: 1,
  essayMaxDifficulty: 5,
  // 是否使用题目原分数
  useOriginalScore: false
});

// 校验规则
const rules = {
  'paper.paperName': [{ required: true, message: '请输入试卷名称', trigger: 'blur' }],
  'paper.classId': [{ required: true, message: '请选择班级', trigger: 'change' }],
  'paper.duration': [{ required: true, message: '请输入考试时长', trigger: 'blur' }],
  'paper.startTime': [{ required: true, message: '请选择开始时间', trigger: 'blur' }],
  'paper.endTime': [{ required: true, message: '请选择结束时间', trigger: 'blur' }],
  'chapterIds': [{ required: true, message: '请选择章节范围', trigger: 'change' }]
};

// 处理分数设置类型变化
const handleScoreTypeChange = (value) => {
  // 更新paper对象中的useOriginalScore属性
  form.paper.useOriginalScore = !value;
};

// 计算总分
const calculateTotalScore = () => {
  if (!useCustomScores.value) {
    // 使用题目原有分数计算总分
    let total = 0;
    
    // 累加每种题型的原始分数
    if (previewData.singleChoice && previewData.singleChoice.length > 0) {
      total += previewData.singleChoice.reduce((sum, q) => sum + (q.score || 0), 0);
    }
    
    if (previewData.multiChoice && previewData.multiChoice.length > 0) {
      total += previewData.multiChoice.reduce((sum, q) => sum + (q.score || 0), 0);
    }
    
    if (previewData.judgment && previewData.judgment.length > 0) {
      total += previewData.judgment.reduce((sum, q) => sum + (q.score || 0), 0);
    }
    
    if (previewData.fillBlank && previewData.fillBlank.length > 0) {
      total += previewData.fillBlank.reduce((sum, q) => sum + (q.score || 0), 0);
    }
    
    if (previewData.essay && previewData.essay.length > 0) {
      total += previewData.essay.reduce((sum, q) => sum + (q.score || 0), 0);
    }
    
    return total;
  }
  
  // 使用统一设置的分数
  let total = 0;
  total += form.singleChoiceCount * form.singleChoiceScore;
  total += form.multiChoiceCount * form.multiChoiceScore;
  total += form.judgmentCount * form.judgmentScore;
  total += form.fillBlankCount * form.fillBlankScore;
  total += form.essayCount * form.essayScore;
  return total;
};

// 处理内容，确保图片和数学公式正确显示
const processContent = (content) => {
  if (!content) return '';
  
  // 处理图片大小
  let processedContent = content;
  const tempDiv = document.createElement('div');
  tempDiv.innerHTML = processedContent;
  const images = tempDiv.querySelectorAll('img');
  images.forEach(img => {
    img.style.maxWidth = '100%';
    img.style.height = 'auto';
    img.style.objectFit = 'contain';
  });
  
  return tempDiv.innerHTML;
};

// 渲染填空题内容
const renderFillBlankQuestion = (content) => {
  if (!content) return '';
  return content.replace(/_{3,}/g, '<span class="blank-line">_________</span>');
};

// MathJax加载和渲染
const loadMathJax = () => {
  return new Promise((resolve) => {
    if (window.MathJax) {
      try {
        if (window.MathJax.typesetPromise) {
          window.MathJax.typesetPromise();
        } else if (window.MathJax.typeset) {
          window.MathJax.typeset();
        }
      } catch (e) {
        console.error('MathJax已加载但渲染失败:', e);
      }
      resolve(window.MathJax);
      return;
    }
    
    // 先创建配置
    window.MathJax = {
      tex: {
        inlineMath: [['$', '$'], ['\\(', '\\)']],
        displayMath: [['$$', '$$'], ['\\[', '\\]']]
      },
      svg: {
        fontCache: 'global'
      },
      output: {
        // 设置不显示溢出指示器
        overflow: false
      },
      startup: {
        ready: () => {
          console.log('MathJax is ready');
          window.MathJax.startup.defaultReady();
          resolve(window.MathJax);
        }
      }
    };
    
        // 然后加载脚本
    const script = document.createElement('script');
    script.src = 'https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-mml-chtml.js';
    script.async = true;
    script.onload = () => {
      console.log('MathJax脚本已加载');
    };
    script.onerror = (e) => {
      console.error('MathJax加载失败:', e);
      // 尝试加载备用CDN
      const backupScript = document.createElement('script');
      backupScript.src = 'https://cdnjs.cloudflare.com/ajax/libs/mathjax/3.2.0/es5/tex-mml-chtml.js';
      backupScript.async = true;
      document.head.appendChild(backupScript);
    };
    document.head.appendChild(script);
  });
};

// 预览对话框打开后渲染数学公式
const renderMathInPreview = async () => {
  console.log('开始渲染公式');
  await nextTick();
  
  try {
    const mathJax = await loadMathJax();
    console.log('MathJax已加载', mathJax);
    
    // 确保内容已经渲染到DOM
    await nextTick();
    
    // 添加CSS来隐藏数学公式区域的滚动条
    const style = document.createElement('style');
    style.innerHTML = `
      .MJX-TEX { overflow: hidden !important; }
      .MathJax { overflow: hidden !important; }
      mjx-container { overflow: hidden !important; }
    `;
    document.head.appendChild(style);
    
    // 尝试多种方法渲染公式
    if (previewContainer.value) {
      if (mathJax.typesetPromise) {
        await mathJax.typesetPromise([previewContainer.value]);
        console.log('使用typesetPromise方法渲染完成');
      } else if (mathJax.typeset) {
        mathJax.typeset([previewContainer.value]);
        console.log('使用typeset方法渲染完成');
      } else {
        console.error('找不到MathJax的渲染方法');
      }
    } else {
      console.error('找不到预览容器');
    }
  } catch (error) {
    console.error('MathJax渲染错误:', error);
    
    // 作为备选方案，使用KaTeX尝试渲染
    try {
      if (!window.katex) {
        const link = document.createElement('link');
        link.rel = 'stylesheet';
        link.href = 'https://cdn.jsdelivr.net/npm/katex@0.16.4/dist/katex.min.css';
        document.head.appendChild(link);
        
        const script = document.createElement('script');
        script.src = 'https://cdn.jsdelivr.net/npm/katex@0.16.4/dist/katex.min.js';
        script.onload = () => {
          const autoRenderScript = document.createElement('script');
          autoRenderScript.src = 'https://cdn.jsdelivr.net/npm/katex@0.16.4/dist/contrib/auto-render.min.js';
          autoRenderScript.onload = () => {
            window.renderMathInElement(previewContainer.value, {
              delimiters: [
                {left: '$$', right: '$$', display: true},
                {left: '$', right: '$', display: false}
              ]
            });
          };
          document.head.appendChild(autoRenderScript);
        };
        document.head.appendChild(script);
      } else {
        window.renderMathInElement(previewContainer.value, {
          delimiters: [
            {left: '$$', right: '$$', display: true},
            {left: '$', right: '$', display: false}
          ]
        });
      }
    } catch (katexError) {
      console.error('KaTeX渲染备选方案也失败:', katexError);
    }
  }
};

// 获取章节树
const getChapterData = async () => {
  try {
    const res = await getChapters();
    // 添加根节点"离散数学"
    if (res.data && res.data.length > 0) {
      // 预处理章节树，确保选择父节点时能选中所有子节点
      const rootNode = {
        chapterId: 0,
        chapterName: '离散数学',
        children: preprocessChapterTree(res.data)
      };
      chapterTree.value = [rootNode];
    } else {
      chapterTree.value = res.data || [];
    }
  } catch (err) {
    console.error('获取章节数据失败:', err);
    ElMessage.error('获取章节数据失败');
  }
};

// 预处理章节树，确保节点有正确的属性
const preprocessChapterTree = (nodes) => {
  if (!nodes || !nodes.length) return [];
  
  return nodes.map(node => {
    // 递归处理子节点
    if (node.children && node.children.length > 0) {
      node.children = preprocessChapterTree(node.children);
    }
    return node;
  });
};

// 获取班级列表
const getClassData = async () => {
  try {
    // 从store中获取当前用户角色
    const userStore = useUserStore();
    const roles = userStore.roles;
    
    if (roles.includes('teacher')) {
      // 教师角色：只获取自己任课的班级
      const res = await getMyClasses();
      classList.value = res.data || [];
    } else {
      // 管理员角色：获取所有班级
      const res = await listGrade();
      classList.value = res.rows.filter(item => item.status === 0); // 筛选启用状态的班级
    }
  } catch (err) {
    console.error('获取班级数据失败:', err);
    ElMessage.error('获取班级数据失败');
  }
};

// 提交表单
const handleSubmit = () => {
  formRef.value.validate(async (valid) => {
    if (valid) {
      try {
        // 构建请求参数，确保和预览的是同一批题目
        const params = {
          paper: form.paper,
          // 不再需要单独设置useOriginalScore，已经在paper对象中
          
          // 使用预览时的题目ID而不是重新生成
          selectedQuestions: [
            ...previewData.singleChoice || [],
            ...previewData.multiChoice || [],
            ...previewData.judgment || [],
            ...previewData.fillBlank || [],
            ...previewData.essay || []
          ].map(q => {
            return {
              questionId: q.questionId,
              questionScore: getQuestionScore(q)
            };
          }),
        };

        const res = await createAutomaticPaper(params);
        ElMessage.success('创建试卷成功');
        // 跳转到试卷列表页
        router.push('/paper/paper');
      } catch (err) {
        console.error('创建试卷失败:', err);
        ElMessage.error(err.message || '创建试卷失败');
      }
    } else {
      return false;
    }
  });
};

// 预览试卷
const handlePreview = async () => {
  formRef.value.validate(async (valid) => {
    if (valid) {
      previewDialogVisible.value = true;
      previewLoading.value = true;
      
      try {
        // 构建请求参数
        const params = {
          paper: form.paper, // 传递包含useOriginalScore的paper对象
          chapterIds: form.chapterIds,
          
          // 每种题型使用单独的难度设置
          // 单选题参数
          singleChoiceCount: form.singleChoiceCount,
          singleChoiceScore: form.singleChoiceScore,
          singleChoiceMinDifficulty: form.singleChoiceMinDifficulty,
          singleChoiceMaxDifficulty: form.singleChoiceMaxDifficulty,
          
          // 多选题参数
          multiChoiceCount: form.multiChoiceCount,
          multiChoiceScore: form.multiChoiceScore,
          multiChoiceMinDifficulty: form.multiChoiceMinDifficulty,
          multiChoiceMaxDifficulty: form.multiChoiceMaxDifficulty,
          
          // 判断题参数
          judgmentCount: form.judgmentCount,
          judgmentScore: form.judgmentScore,
          judgmentMinDifficulty: form.judgmentMinDifficulty,
          judgmentMaxDifficulty: form.judgmentMaxDifficulty,
          
          // 填空题参数
          fillBlankCount: form.fillBlankCount,
          fillBlankScore: form.fillBlankScore,
          fillBlankMinDifficulty: form.fillBlankMinDifficulty,
          fillBlankMaxDifficulty: form.fillBlankMaxDifficulty,
          
          // 简答题参数
          essayCount: form.essayCount,
          essayScore: form.essayScore,
          essayMinDifficulty: form.essayMinDifficulty,
          essayMaxDifficulty: form.essayMaxDifficulty
        };

        const res = await previewAutomaticPaper(params);
        
        // 分类处理题目
        previewData.singleChoice = res.data.filter(q => q.questionType === 0);
        previewData.multiChoice = res.data.filter(q => q.questionType === 1);
        previewData.judgment = res.data.filter(q => q.questionType === 2);
        previewData.fillBlank = res.data.filter(q => q.questionType === 3);
        previewData.essay = res.data.filter(q => q.questionType === 4);
        
      } catch (err) {
        console.error('预览试卷失败:', err);
        ElMessage.error(err.message || '预览试卷失败');
      } finally {
        previewLoading.value = false;
      }
    } else {
      return false;
    }
  });
};

// 重置表单
const resetForm = () => {
  formRef.value.resetFields();
  useCustomScores.value = true;
  form.paper.useOriginalScore = false;
  
  // 设置默认开始时间为当前时间
  const now = new Date();
  form.paper.startTime = formatLocalDateTime(now);
  
  // 设置默认结束时间
  const endTime = new Date(now.getTime() + form.paper.duration * 60 * 1000);
  form.paper.endTime = formatLocalDateTime(endTime);
};

// 预加载MathJax和初始化数据
onMounted(() => {
  getChapterData();
  getClassData();
  loadMathJax();
  
  // 设置默认开始时间为当前时间
  const now = new Date();
  form.paper.startTime = formatLocalDateTime(now);
    
  // 设置默认结束时间
  const endTime = new Date(now.getTime() + form.paper.duration * 60 * 1000);
  form.paper.endTime = formatLocalDateTime(endTime);
});
</script>

<style>
.ql-editor {
  min-height: 200px;
}

.ql-toolbar {
  background-color: #f8f8f8;
}

.ql-container {
  font-size: 14px;
}

/* 添加全局样式确保MathJax渲染正确 */
.MathJax {
  display: inline-block !important;
  margin: 0 0.2em;
  overflow: hidden !important;
}

/* 添加额外的样式确保KaTeX备选方案也能正确显示 */
.katex { 
  font-size: 1.1em !important;
  overflow: hidden !important;
}

/* 隐藏数学公式渲染区域的滚动条 */
mjx-container {
  overflow: hidden !important;
}

mjx-math {
  overflow: hidden !important;
}

.MJX-TEX {
  overflow: hidden !important;
}

/* 确保公式不会被裁剪 */
mjx-container[jax="CHTML"][display="true"] {
  max-width: 100%;
  overflow-x: auto;
  overflow-y: hidden;
}
</style>

<style scoped>
.app-container {
  padding: 20px;
}
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.main-title {
  font-size: 18px;
  font-weight: bold;
  color: #303133;
}
.section-header {
  position: relative;
  font-size: 16px;
  font-weight: 600;
  color: #303133;
  margin: 20px 0;
  padding-left: 12px;
  border-left: 3px solid #409EFF;
  line-height: 1.2;
  background-color: #f5f7fa;
  padding: 10px 15px;
  border-radius: 4px;
}
.w-100 {
  width: 100%;
}
.text-center {
  text-align: center;
  line-height: 32px;
}
.score-setting-toggle {
  display: flex;
  justify-content: flex-end;
  margin: 5px 0;
}
.paper-preview {
  padding: 20px;
}
.paper-header {
  text-align: center;
  margin-bottom: 30px;
}
.paper-header h1 {
  font-size: 24px;
  font-weight: bold;
  margin-bottom: 10px;
}
.paper-info {
  display: flex;
  justify-content: center;
  gap: 20px;
}
.paper-content {
  padding: 0 10px;
}
.question-section {
  margin-bottom: 30px;
}
.question-section h2 {
  font-size: 18px;
  font-weight: bold;
  margin-bottom: 15px;
  border-bottom: 1px solid #ddd;
  padding-bottom: 8px;
}
.question-item {
  margin-bottom: 20px;
}
.question-title {
  font-size: 16px;
  margin-bottom: 10px;
  line-height: 1.5;
}
.question-options {
  padding-left: 20px;
}
.question-option {
  margin-bottom: 8px;
  line-height: 1.5;
  display: flex;
  align-items: flex-start;
}
.option-label {
  font-weight: bold;
  margin-right: 5px;
  min-width: 25px;
}
.option-content {
  flex: 1;
}
.blank-line {
  display: inline-block;
  min-width: 120px;
  border-bottom: 1px solid #000;
  margin: 0 5px;
  text-align: center;
}
.empty-data {
  text-align: center;
  color: #999;
  padding: 50px 0;
}
.button-group {
  display: flex;
  justify-content: center;
  margin-top: 30px;
}
.button-group .el-button {
  margin: 0 10px;
}
.preview-container {
  padding: 15px;
}
.preview-container img {
  max-width: 100% !important;
  height: auto !important;
  object-fit: contain !important;
}
.question-title img {
  max-width: 100% !important;
  height: auto !important;
  object-fit: contain !important;
}
.question-option img {
  max-width: 100% !important;
  height: auto !important;
  object-fit: contain !important;
}
/* 修改星级评分器样式 */
:deep(.el-rate) {
  margin-top: 5px;
  display: flex;
  height: 32px;
  line-height: 32px;
}
:deep(.el-rate__icon) {
  font-size: 18px;
  margin-right: 3px;
}
:deep(.el-rate__decimal) {
  top: 0;
}

/* 优化章节选择下拉框样式 */
:deep(.el-tree-select) {
  width: 100%;
}

:deep(.el-select__tags) {
  display: flex;
  flex-wrap: wrap;
  max-width: 100%;
}

:deep(.el-select__tags-text) {
  max-width: 120px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
.score-tag {
  color: #409EFF;
  font-weight: bold;
  margin-right: 5px;
}
</style>